<template>
  <div class="text-black">
    <PageLayout>
      <template #nav>
        <div class="report-header">
          <div class="top">
            <div class="left"> 审核管理 / 详情 </div>
            <div class="right"></div>
          </div>
          <div class="bottom">
            <div class="left">
              <div class="back" @click="handleBack"> &lt; 返回 </div>
              <div class="line"></div>
              <div class="title">
                {{ activeItem.title }}
              </div>
            </div>
            <div class="right">
              <el-button
                plain
                type="primary"
                v-if="status === CHECK_STATUS.PENDING_APPROVAL"
                @click="handleShowCheckDialog"
                v-hasPermi="['handBook:checkBook:checkBtn']"
              >
                审核
              </el-button>
              <el-button
                plain
                type="danger"
                @click="handleRevoke"
                v-if="status === CHECK_STATUS.PENDING_APPROVAL"
                v-hasPermi="['handBook:checkBook:checkBtn']"
                >撤销
              </el-button>
            </div>
          </div>
        </div>
      </template>
      <template #main>
        <div class="main-iframe">
          <!-- main{{ activeItem }}{{ taskInfo }} -->
          <IframePage
            :formId="activeItem.instId"
            :recordId="activeItem.id"
            :viewModel="viewModel"
            bizModule="NursingHandbookReal"
            @saveFormData="handleSaveFormData"
            :key="activeItem.id + viewModel"
            v-if="activeItem.id"
          ></IframePage>
          <div v-else class="empty-info"><span class="left-tips">请创建或选择手册</span></div>
        </div>
      </template>
      <template #right>
        <RightSide :processList="processList"></RightSide>
      </template>
    </PageLayout>

    <checkDialog :options="checkOptions" @confirm="handleCheckConfirm"></checkDialog>
  </div>
</template>
<script setup>
  import {
    computed,
    onBeforeMount,
    onMounted,
    ref,
    reactive,
    nextTick,
    defineAsyncComponent,
  } from 'vue';
  import PageLayout from '@/components/PageLayout/index.vue';
  import HeaderBar from '@/components/PageLayout/Side/Header/index.vue';

  import {
    deleteHandbookRecord as deleteData,
    postHandbookRecordPage as queryList,
  } from '@/api/handbookRecord/index';
  import { useSubMenu } from '@/hooks/useSubMenu/index';
  import { postHandbookTemplatePage } from '@/api/handbookTemplate/index';
  import { getStationList } from '@/api/system/station';
  import { useStore } from 'vuex';
  import { useHandleData } from '@/hooks/useHandleData/index';
  import { useBookList } from '@/hooks/useBookList/index';
  import { useDeptData } from '@/hooks/useDeptData/index';
  import { useProcess } from '@/hooks/useProcess/index';
  import { CHECK_STATUS } from '@/constants/status';
  import { useRouter } from 'vue-router';

  const checkDialog = defineAsyncComponent(() =>
    import('@/views/business/objectives/components/checkDialog.vue'),
  );

  const RightSide = defineAsyncComponent(() =>
    import('@/components/PageLayout/Side/Right/index.vue'),
  );

  const IframePage = defineAsyncComponent(() => import('@/components/IframePage/iframe.vue'));
  const router = useRouter();
  const store = useStore();
  const allEnums = store.state.app.allEnums;
  const userId = store.getters.userId;
  const { deptData, getDeptData } = useDeptData();

  const searchName = ref('');
  const handleMoreFilter = () => {
    filterOptions.visible = true;
  };
  const handleFilterOwner = (val) => {
    handleSearch({ field: 'createBy', value: val ? userId : null });
  };
  const handleRename = (item) => {
    handleUpdate('重命名', item);
  };
  const handleMove = (item) => {
    handleMoveUpdate('移动到', item);
  };
  const addOption = ref({
    width: 760,
    title: '新建',
    visible: false,
    editStatus: false,
    defaultValue: {},
    cate: [],
    templateList: [],
    typeId: '',
  });
  const moveOptions = reactive({
    width: 760,
    title: '移动到',
    visible: false,
    editStatus: false,
    defaultValue: {},
    width: 500,
    cate: [],
    typeId: '',
  });
  let dialogOptions = reactive({
    title: '',
    visible: false,
    defaultValue: {},
    width: 500,
    cate: [],
  });
  const checkOptions = reactive({
    width: 500,
    title: '审核',
    modal: false,
    visible: false,
    top: '30vh',
    cancelText: '取消',
    confirmText: '确定',
    defaultValue: '',
  });
  const handleShowCheckDialog = (row) => {
    checkOptions.visible = true;
    checkOptions.defaultValue = taskInfo;
  };
  const filterOptions = reactive({
    width: 500,
    title: '高级筛选',
    modal: false,
    visible: false,
    top: '30vh',
    cancelText: '取消',
    confirmText: '确定',
  });
  // 高级筛选
  const handleFilterConfirm = async (formData) => {
    filterOptions.visible = false;
    console.log('handleFilterConfirm', formData);
    let params = {
      ...formData,
      deptId: formData.deptId ? formData.deptId[formData.deptId.length - 1] : null,
      createTime: !formData?.createTime?.length
        ? null
        : {
            startValue: formData.createTime[0],
            endValue: formData.createTime[1],
          },
    };

    searchParams.value = params;
    await queryData(searchParams.value);
    // nextTick(() => {
    //   searchName.value = formData.title;
    // });
  };
  const viewModel = ref('editor');
  // 新建
  const handleShowAddDialog = () => {
    addOption.value.visible = true;
    addOption.value.title = '新建';
    addOption.value.cate = formTypeList.value;
    addOption.value.defaultValue = {};
    addOption.value.templateList = templateList.value;
    addOption.value.typeId = routerId;
  };

  function handleConfirm() {
    dialogOptions.visible = false;
    addOption.value.visible = false;
    queryData(searchParams.value);
  }

  function handleClose() {
    dialogOptions.visible = false;
    dialogOptions.defaultValue = {};
    moveOptions.visible = false;
    moveOptions.defaultValue = {};
    addOption.value.visible = false;
  }
  // 编辑
  function handleUpdate(title, row) {
    dialogOptions.title = title;
    dialogOptions.visible = true;
    dialogOptions.editStatus = true;
    dialogOptions.defaultValue = JSON.parse(JSON.stringify(row));
    dialogOptions.cate = formTypeList.value;
  }
  // 移动
  function handleMoveUpdate(title, row) {
    moveOptions.title = title;
    moveOptions.visible = true;
    moveOptions.editStatus = true;
    moveOptions.defaultValue = JSON.parse(JSON.stringify(row));
    moveOptions.cate = formTypeList.value;
  }
  // 审核
  function handleCheckConfirm(formData) {
    checkOptions.visible = false;
    console.log('handleCheckConfirm', formData);
    let params = {
      ...formData,
    };
    console.log('params', params);
  }
  async function handleRevoke() {
    await useHandleData(deleteData, { id: row.id }, `请问是否确定撤销这条审核记录`);
  }
  // 删除数据
  async function handleDelete(row) {
    await useHandleData(deleteData, { id: row.id }, `确认删除${row.title}`);
    queryData(searchParams.value);
  }
  function handleBack() {
    router.go(-1);
  }
  // 保存数据
  function handleSaveFormData(data) {
    console.log('handleSaveFormData', data);
    queryData(searchParams.value);
    // activeItem.value = {};
  }

  const templateList = ref([]);
  const activeItem = ref({});
  async function handleClickItem(item) {
    console.log('handleClickItem', item);
    viewModel.value = item.state >= CHECK_STATUS.PENDING_APPROVAL ? 'view' : 'editor';
    activeItem.value = item;
    processList.value = [];
    item?.processId && initProcess(item.processId);
  }
  const { initProcess, processList, taskInfo } = useProcess();

  const { getSubMenu, subMenu, routerId, routeName } = useSubMenu();
  const templateSearchParams = reactive({
    pageSize: 10000,
    pageNum: 1,
    formType: routerId,
  });
  async function queryBookTemplate() {
    let ret = await postHandbookTemplatePage(templateSearchParams);
    if (ret.code === 200) {
      templateList.value = ret.data.records;
    }
  }

  //岗位列表
  const positionList = ref([]);
  async function queryPositionList() {
    let ret = await getStationList();
    if (ret.code === 200) {
      positionList.value = [{ id: '', name: '全部' }].concat(ret.data);
    }
  }

  const formTypeList = ref([]);
  const searchParams = ref({
    // routerId: routerId,
    id: '',
  });

  async function handleSearch(params = {}) {
    searchParams.value[params.field] = params.value;
    await queryData(searchParams.value);
  }

  const dataField = {
    field: 'list',
  };
  const { queryData, treeList } = useBookList({ queryList, formTypeList, dataField });
  let recordStates = ref([]);
  onMounted(async () => {
    let docId = router.currentRoute.value.query.id;
    searchParams.value.id = docId;
    await queryData(searchParams.value);
  });
</script>
<style lang="scss" scoped>
  .main-iframe {
    min-width: 600px;
    width: 80%;
    margin: 10px auto;
    display: block;
    background-color: #fff;
    height: 96%;
    overflow: scroll;
    position: relative;
  }
  .report-header {
    height: 72px;
    background: #ffffff;
    border-radius: 4px;
    margin: 0px;
    padding: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    .top,
    .bottom {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left,
      .right {
        display: flex;
        align-items: center;
      }
    }
    .top {
      font-size: 12px;
      color: #666666;
    }
    .bottom {
      font-size: 14px;
    }
    .back {
      color: #358f80;
      cursor: pointer;
    }
    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background-color: #e5e5e5;
    }
    .title {
      font-size: 16px;
      font-weight: bold;
      color: #000000;
    }
  }
</style>
